package com.chushouya.manager.dao.repository;

import com.chushouya.manager.dao.entity.LoginLogEntity;
import com.chushouya.manager.dao.mapper.LoginLogEntityMapper;
import com.chushouya.manager.dto.admin.log.LoginLogQueryDTO;
import com.general.framework.core.lang.Dates;
import com.general.framework.core.lang.Numbers;
import com.general.framework.core.lang.Strings;
import com.general.framework.core.schema.PageResult;
import com.general.framework.data.mybatis.BaseRepository;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.Objects;

@Repository
public class LoginLogRepository extends BaseRepository<LoginLogEntityMapper, LoginLogEntity, Long> {

    public void saveOperateLog(LoginLogEntity loginLog) {
        this.insertSelective(loginLog);
    }

    public void cleanLogin(Integer cleanBeforeDays) {
        if (!Objects.equals(cleanBeforeDays, Numbers.INTEGER_ZERO)) {
            final Date date = Dates.addDays(new Date(), - cleanBeforeDays);
            Example example = this.buildExample();
            example.and().andLessThan("loginTime", Dates.getFirstTime(date));
            this.deleteByExample(example);
        } else {
            this.mapper.clean();
        }
    }

    public PageResult<LoginLogEntity> selectLoginInfoPageResult(LoginLogQueryDTO query) {
        Example example = this.buildExample();
        if(Strings.isNotEmpty(query.getUserName())){
            example.and().andEqualTo("userName", query.getUserName());
        }
        if(Objects.nonNull(query.getStatus())){
            example.and().andEqualTo("status", query.getStatus());
        }
        if(Objects.nonNull(query.getBeginTime()) && Objects.nonNull(query.getEndTime())){
            example.and().andGreaterThan("loginTime", query.getBeginTime());
            example.and().andLessThan("loginTime", query.getEndTime());
        }
        example.orderBy("loginTime").desc();
        return this.selectPage(query.getPageRequest(), example);
    }
}
